﻿CREATE PROCEDURE [dbo].[CustomerReturnLinesDelete]
(--возврат от покупателя
	@Original_Id int,
	@Original_MD datetime
)
AS
DECLARE @strMsg nvarchar(500), @intRet int, @intErrCode int
DECLARE	@orgDocId int, @orgPartyId int, @orgDocDate smalldatetime, @orgQntty int
DECLARE @intInputCount int, @intOutputCount int

SET NOCOUNT ON
IF (@Original_Id Is Null) OR (@Original_MD Is Null)
BEGIN
	SELECT @intErrCode = 1, @strMsg = 'Неправильные параметры в вызове процедуры ' + Object_Name(@@Procid) + ' !'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

SELECT @orgDocId = L.DocId, @orgPartyId = L.PartyId, 
@orgQntty = L.Qntty, @orgDocDate = D.DocDate
FROM CA.GoodsDocLines L INNER JOIN CA.Documents AS D ON L.DocId = D.Id
WHERE L.Id = @Original_Id AND L.MD = @Original_MD
IF (@@rowcount <> 1)
BEGIN
	SELECT @intErrCode = 2, 
	@strMsg = 'Данные изменены после последнего запроса!'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

SET @orgQntty = @orgQntty * -1
EXEC @intRet = dbo.CheckPartyFlow @orgPartyId, @orgQntty, @orgDocDate, @intInputCount OUTPUT, @intOutputCount OUTPUT
IF @intRet <> 0 RETURN @intRet
	
	SET NOCOUNT OFF;
DELETE FROM [CA].[GoodsDocLines] WHERE Id = @Original_Id AND MD = @Original_MD




